package com.xiaolong.cloud.feign.adapter;

import java.io.IOException;
import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;
import org.jetbrains.annotations.NotNull;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class FeignClientLogInterceptor implements Interceptor {
    private static final Logger log = LoggerFactory.getLogger(FeignClientLogInterceptor.class);

    @Override
    @NotNull
    public Response intercept(Interceptor.Chain chain) throws IOException {
        Request request = chain.request();
        long t1 = System.nanoTime();
        log.info(String.format("发送请求 %s on %s%n%s", request.url(), chain.connection(), request.headers()));
        Response response = chain.proceed(request);
        long t2 = System.nanoTime();
        ResponseBody responseBody = response.peekBody(1048576L);
        log.info(String.format("接收响应: [%s] %n返回json:【%s】 %.1fms%n", response.request().url(), responseBody.string(), (double)(t2 - t1) / 1000000.0));
        return response;
    }
}